package com.qida.clm.core.imageloader;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.ImageView;

import com.android.volley.toolbox.ImageLoader;

/**
 * Created by edgar on 2016/2/17.
 */
public class AsyncLoaderImageView extends ImageView{

    private ImageLoaderControl mImageLoaderControl;

    public AsyncLoaderImageView(Context context) {
        super(context);
    }

    public AsyncLoaderImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public AsyncLoaderImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    private void ensureImageLoaderControl(){
        if(mImageLoaderControl == null){
            mImageLoaderControl = new ImageLoaderControl();
        }
    }
    /**
     * Sets URL of the image that should be loaded into this view. Note that calling this will
     * immediately either set the cached image (if available) or the default image specified by
     * {@link AsyncLoaderImageView#setDefaultImageResId(int)} on the view.
     *
     * NOTE: If applicable, {@link AsyncLoaderImageView#setDefaultImageResId(int)} and
     * {@link AsyncLoaderImageView#setErrorImageResId(int)} should be called prior to calling
     * this function.
     *
     * @param url The URL that should be loaded into this ImageView.
     * @param imageLoader ImageLoader that will be used to make the request.
     */
    public void setImageUrl(String url, ImageLoader imageLoader) {
        ensureImageLoaderControl();
        mImageLoaderControl.setImageView(this,url,imageLoader);
    }

    /**
     * Sets the default image resource ID to be used for this view until the attempt to load it
     * completes.
     */
    public void setDefaultImageResId(int defaultImage) {
        ensureImageLoaderControl();
        mImageLoaderControl.setDefaultImageResId(defaultImage);
    }

    /**
     * Sets the error image resource ID to be used for this view in the event that the image
     * requested fails to load.
     */
    public void setErrorImageResId(int errorImage) {
        ensureImageLoaderControl();
        mImageLoaderControl.setErrorImageResId(errorImage);
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        ensureImageLoaderControl();
        mImageLoaderControl.loadImageIfNecessary(true);
    }

    @Override
    protected void onDetachedFromWindow() {
        ensureImageLoaderControl();
        mImageLoaderControl.onDetachedFromWindow();
        super.onDetachedFromWindow();
    }

    @Override
    protected void drawableStateChanged() {
        super.drawableStateChanged();
        invalidate();
    }
}